﻿@page "/login"
@using ProjectTracker.Library.Security
@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Authentication.Cookies
@using System.Security.Claims
@inject Csla.Blazor.State.StateManager StateManager
@inject IHttpContextAccessor httpContextAccessor
@inject IDataPortal<UserValidation> portal
@inject NavigationManager NavigationManager

<PageTitle>Project Tracker - Login</PageTitle>

<h1>Login</h1>

<div>
  <EditForm Model="userInfo" OnSubmit="LoginUser" FormName="loginform">
      <div>
          <label>Username</label>
          <InputText @bind-Value="userInfo.Username" />
      </div>
      <div>
          <label>Password</label>
          <InputText type="password" @bind-Value="userInfo.Password" />
      </div>
      <button>Login</button>
  </EditForm>
</div>

<div style="background-color:lightgray">
  <p>User identities:</p>
  <p>admin, admin<br />manager, manager</p>
</div>

<div><p class="alert-danger">@Message</p></div>

@code {

    [SupplyParameterFromForm]
    public UserInfo userInfo { get; set; } = new();

    public string Message { get; set; } = "";

    private async Task LoginUser()
    {
        await StateManager.InitializeAsync();
        Message = "";
        var userValidation = await portal.ExecuteAsync(userInfo.Username, userInfo.Password);
        ClaimsPrincipal principal;
        if (userValidation.IsValid)
        {
            // create authenticated principal
            var identity = new ClaimsIdentity("custom");
            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, userInfo.Username, ClaimValueTypes.String));
            foreach (var item in userValidation.Roles)
                claims.Add(new Claim(ClaimTypes.Role, item, ClaimValueTypes.String));
            identity.AddClaims(claims);
            principal = new ClaimsPrincipal(identity);
            var httpContext = httpContextAccessor.HttpContext;
            if (httpContext is not null)
            {
                AuthenticationProperties authProperties = new AuthenticationProperties();
                await httpContext.SignInAsync(
                  CookieAuthenticationDefaults.AuthenticationScheme,
                  principal,
                  authProperties);
                NavigationManager.NavigateTo("/");
            }
        }
        else
        {
            Message = "Invalid credentials";
            //StateHasChanged();
        }
    }


    public class UserInfo
    {
        public string Username { get; set; } = string.Empty;
        public string Password { get; set; } = string.Empty;
    }
}
